
#ifndef __LWP_USERAGENT_H__
#define __LWP_USERAGENT_H__

#include "../knutil.h"
#include "../URI.h"
#include "../HTTP.h"
#include "../HTTP/Connection.h"
#include "../HTTP/Cookie.h"
#include "const.h"

#include <string>
#include <memory>

namespace LWP {



class UserAgent
{
public:
	UserAgent(): user_agent(LWP::LWP_AGENT)
	{
	}

	HTTP::ResponseObject request(const HTTP::RequestObject& req) const
	{
		HTTP::RequestObject nreq = req;
		nreq.test_add_header("User-Agent", user_agent);
		nreq.test_add_header("Connection", "close");
		HTTP::ResponseObject resp(req.host());
		redirectable_request(nreq, resp);
		return resp;
	}
	
	HTTP::ResponseObject head(const std::string& url, const HTTP::HttpHeader& header=HTTP::HttpHeader()) const
	{
		HTTP::RequestObject req(url, HTTP::HttpRequestType::HEAD);
		config_header(req, header);
		HTTP::ResponseObject resp(req.host());
		redirectable_request(req, resp);
		update_cookie(resp);
		return resp;
	}
	HTTP::ResponseObject get(const std::string& url, const HTTP::HttpHeader& header=HTTP::HttpHeader()) const
	{
		HTTP::RequestObject req(url, HTTP::HttpRequestType::GET);
		config_header(req, header);
		HTTP::ResponseObject resp(req.host());
		redirectable_request(req, resp);
		update_cookie(resp);
		return resp;
	}
	HTTP::ResponseObject post(const std::string& url, const HTTP::HttpHeader& header=HTTP::HttpHeader(), const HTTP::HttpForm& form=HTTP::HttpForm()) const
	{
		HTTP::RequestObject req(url, HTTP::HttpRequestType::POST);
		config_header(req, header);
		req.set_form(form);
		HTTP::ResponseObject resp(req.host());
		redirectable_request(req, resp);
		update_cookie(resp);
		return resp;
	}
	HTTP::ResponseObject post(const std::string& url, const HTTP::HttpForm& form) const
	{
		return post(url, HTTP::HttpHeader(), form);
	}

	void agent(const std::string& agent_header)
	{
		user_agent = agent_header;
	}

	void cookie_jar()
	{
		cookie_.reset(new HTTP::Cookies);
	}


private:
	UserAgent(const UserAgent&);
	UserAgent& operator=(const UserAgent&);
private:
	std::string user_agent;
	mutable std::auto_ptr<HTTP::Cookies> cookie_;
private:
	void config_header(HTTP::RequestObject& req, const HTTP::HttpHeader& header) const
	{
		req.set_header(header);
		req.test_add_header("User-Agent", user_agent);
		req.test_add_header("Connection", "close");
		if( cookie_.get() )
		{
			cookie_->add_cookie_header(req);
		}
	}
	void update_cookie(HTTP::ResponseObject& resp) const
	{
		if( cookie_.get() )
		{
			cookie_->extract_cookies(resp);
		}
	}
private:

};


}

#endif


